﻿namespace ChinaUnicom.Tasks
{
    using Avatar;
    using System;
    using ChinaUnicom.Models;
    using Avatar.Schedule;
    using System.Windows;
    using System.Net;
    using System.Linq;

    public class ClientTask : ITask
    {
        public Client Client { get; private set; }

        Context Context { get { return Context.Current; } }

        public ClientTask()
        {
            Client = new Client();
            Client.Occurred = DateTime.Now;
        }

        public void Start()
        {
            if (Started != null)
            {
                Started(this, EventArgs.Empty);
            }

            Factory.Operation.RequestUserInfo(x =>
            {
                try
                {
                    if (x.Status == WebExceptionStatus.Success)
                    {
                        ItemCollection items = Factory.Parser.Parse(x.Result, ItemType.Client);
                        
                        foreach (var item in items)
                        {
                            if (item.Name.IgnoreCaseEquals("客户名称"))
                            {
                                Context.Account.ClientName = item.Value;
                                Client.Name = item.Value;
                            }
                            else if (!item.Value.IsNullOrEmpty())
                            {
                                Client.Items.Add(item);
                            }
                        }

                        Context.Current.Account.LastUpdated = DateTime.Now; 

                        if (Completed != null)
                        {
                            Completed(this, EventArgs.Empty);
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (Failed != null)
                    {
                        Failed(this, new FailedEventArgs(this, ex));
                    }
                }
            });
        }

        public int Delay { get { return 50; } }

        public bool IsUnique { get { return true; } }

        public event EventHandler Completed;

        public event EventHandler Started;

        public event EventHandler<FailedEventArgs> Failed;
    }
}
